package SeedBank

/**
* This information holder class stores the information for a user.
*
*
*/
class User {
	
	String firstName
	String lastName
	String email
	String login
	String password
	String confirmPassword
	String interests 
	String role = "user"
	String state
	String zipCode
	String address
	String country
	String gender
	String climateZone
	String phoneNumber
	String city
	String hashedPass = ""
	int lockCount = 0
	Date dateOfBirth
	Date dateCreated
	def mailBox = []
	
	static hasMany = [seeds:Seed, purchases: Purchase, messages: Mail ]
	
	//email regex: matches:/[a-z][a-z0-9_[-]]*@[a-z][a-z0-9_[-]]*([.][a-z]+)?[.](com|org|net|gov|edu)/
	//names matches: /[A-Za-z][a-z]+/ 
	//phone /[0-9]{10}|([0-9]{3}[-][0-9]{3}[-][0-9]{4})|([(][0-9]{3}[)][-][0-9]{3}[-][0-9]{4})/
	//address: matches:/[0-9]*( [A-Za-z][a-z]*){2,}+/
	//country: matches: /[A-Za-z][a-z]*( [A-Za-z][a-z]*)*|[A-Z]{2,}+/
	/*
	*/
	
	
	/**
	 * Constraints to be imposed on the fields of a user.
	 * 
	 */
	
	static constraints = {
		login(blank:false, nullable:false, unique:true)
		password(blank: false, password: true, validator: {password, obj ->
			def confirmPassword = obj.properties['confirmPassword']
			confirmPassword.equals(password) ? true : ['bad.pass']})
		confirmPassword(blank:false, password:true)
		firstName(blank:false, matches:/[A-Za-z][a-z]*|[A-Z]{2}/)
		lastName(blank:false, matches:/[A-Za-z][a-z]*|[A-Z]{2}/)
		phoneNumber(blank:false, unique:true, matches:/[0-9]{10}|([0-9]{3}[-][0-9]{3}[-][0-9]{4})|([(][0-9]{3}[)][-][0-9]{3}[-][0-9]{4})/)
		email(size:1..100, blank:false, unique:true, email:true)
		zipCode(blank:false, matches:/[0-9]{5}|[0-9]{8}/)
		city(blank:false)
		state(blank:false, matches: "[A-Za-z]{2}")
		address(size:1..100, blank:false )
		country(blank:false)
		climateZone(blank:false)
		dateOfBirth();
		gender(blank:false, inList:["M", "F"])
		role(editable:false, display:false)
		lockCount(display:false)
		hashedPass(display:false)
		mailBox(display:false)
	}
	
	/**
	 * Before a uer object is added to the database, this method is executed.
	 * 
	 */
	
	def beforeInsert = {
		hashedPass = password.encodeAsSHA()
		password = "."
		confirmPassword = "."
	}
	
	static transients = ["admin"]
	
	/**
	 * Creates a string representation of a user.
	 * 
	 * @return A string representation of a user.
	 */
	
	String toString(){
		return "${login}, ${email}"
	}
	
	/**
	 * Tells if the user is an admin
	 * 
	 * @return whether use is admin
	 */
	
	boolean isAdmin(){
		return role=="admin"
	}
	
}
